"""
baseview.py
权限校验基类
"""
import jwt
import json

from django.views import View
from django.conf import settings
from django.http import JsonResponse
from user.models import UserProfile

class BaseView(View):
    def dispatch(self, request, *args, **kwargs):
        #权限逻辑校验
        token = request.META.get("HTTP_AUTHORIZATION")
        try:
            payload = jwt.decode(token, settings.JWT_TOKEN_KEY, algorithms="HS256")
        except Exception as e:
            print("Token校验失败：", e)
            return JsonResponse({'code': 403, 'error': "请登录"})
        username = payload['username']
        user = UserProfile.objects.get(username=username)
        # 给所有套过此装饰器的方法的request参数额外增加了myuser属性
        request.myuser = user
        # 给request对象封装data属性[请求体数据]
        body_data = request.body
        if body_data:
            request.data = json.loads(body_data)
        return super().dispatch(request,*args,**kwargs)